package com.scau.hwadee.examination.controller;

import com.scau.hwadee.examination.vo.ResponseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

/**
 *@author YHX
 *@date 2019/7/26  14:24
 *@description 文件上传和下载的控制类
 */
@Slf4j
@Controller
@RequestMapping("/file")
@Api(tags = "FileController",description = "文件上传和下载模块")
public class FileController {

    private static final String FILE_UPLOAD_DIRECTORY = System.getProperty("user.dir") + File.separator
            + "src" + File.separator + "main" + File.separator
            + "webapp" + File.separator + "static" + File.separator
            + "img" + File.separator;

    /**
     * 上传文件
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ApiOperation(value ="文件上传")
    public ResponseEntity<ResponseVo> fileUpLoad(HttpServletRequest request) {
        long startTime = System.currentTimeMillis();
        ResponseVo vo = ResponseVo.instance();
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        try {
            //检查form中是否有enctype="multipart/form-data"
            if (multipartResolver.isMultipart(request)) {
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                //获取multiRequest 中所有的文件名
                Iterator iter = multiRequest.getFileNames();

                while (iter.hasNext()) {
                    //一次遍历所有文件
                    MultipartFile file = multiRequest.getFile(iter.next().toString());
                    if (file != null) {
                        String path = FILE_UPLOAD_DIRECTORY + file.getOriginalFilename();
                        log.debug("文件上传路劲为：" + path);
                        //上传
                        file.transferTo(new File(path));
                    }
                }
            }
            vo.setMessage("文件上传成功");
        } catch (IOException ioe) {
            log.debug("文件上传出错{}", ioe);
            vo.setMessage("文件上传失败");
        }
        long endTime = System.currentTimeMillis();
        log.debug("运行时间：" + (endTime - startTime) + "ms");
        return new ResponseEntity<>(vo, HttpStatus.OK);
    }

    @RequestMapping(value = "/download", method = RequestMethod.POST)
    @ApiOperation(value = "文件下载")
    public ResponseEntity<ResponseVo> fileDownload(@RequestBody Map<String, String> map) {
        String filePath = map.get("filePath");
        String fileName = map.get("fileName");
        HttpHeaders headers = new HttpHeaders();
        File file = new File(filePath);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", fileName);
        ResponseVo vo = ResponseVo.instance();
        try {
            byte[] bytes = FileUtils.readFileToByteArray(file);
            vo.setData(bytes);
            vo.setMessage("文件下载成功！！！");
            log.debug("文件下载成功");
            return new ResponseEntity<>(vo, headers, HttpStatus.CREATED);
        } catch (Exception e) {
            vo.setMessage("文件下载失败！！！");
            log.debug("文件下载失败");
            return new ResponseEntity<>(vo, headers, HttpStatus.CREATED);
        }
    }
}
